package bdd.daos.impl;

import bdd.DBLink;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import bdd.beans.*;
import bdd.daos.*;

public class DAORoleImpl implements DAORole{
	private DBLink dblink;

	public DAORoleImpl() {	
		super();
		this.dblink = new DBLink(); 
	}
	
	@Override
	public Role save(Role unRole) {
		
		try {
			dblink.connexion();
			this.dblink.setPst(this.dblink.getConnection().prepareStatement("INSERT INTO ROLE (libelle)" +
					" VALUES ('"+unRole.getLibelle()+"')"));
			this.dblink.getPst().executeQuery();
			DAOOutils outil = new DAOOutils();
			unRole.setIdrole(outil.findMaxId("ROLE", "IDROLE"));
		}
		catch(SQLException se) {
			System.out.println("Erreur de requ�te");
		}
		finally{
			dblink.deconnexion();
		}
		return unRole;
	}

	@Override
	public Role find(Integer id) {
		Role unRole = new Role();
		unRole.setIdrole(id);
		try {
			dblink.connexion();
			this.dblink.setPst(this.dblink.getConnection().prepareStatement("SELECT * FROM ROLE WHERE IDROLE = " + id));
			ResultSet rs = this.dblink.getPst().executeQuery();
			while(rs.next()) {
				unRole.setLibelle(rs.getString("LIBELLE"));
			}
		}
		catch(SQLException se) {
			System.out.println("Erreur de requ�te");
		}
		finally{
			dblink.deconnexion();
		}
		return unRole;
	}

	@Override
	public List<Role> findAll() {
		List<Role> Lstretour = new ArrayList<Role>();
		try {
			this.dblink.connexion();
			this.dblink.setPst(this.dblink.getConnection().prepareStatement("SELECT * FROM ROLE"));
			ResultSet rs = this.dblink.getPst().executeQuery();
			while(rs.next()) {
				Role retour = new Role();
				retour.setLibelle(rs.getString("LIBELLE"));
				retour.setIdrole(rs.getInt("IDROLE"));
				Lstretour.add(retour);
			}		
		}
		catch(SQLException se) {
			System.out.println("Erreur de requ�te" + se);
		}
		finally{
			this.dblink.deconnexion();
		}
		return Lstretour;
	}

	@Override
	public void update(Role o) {
		try {
			this.dblink.connexion();
			String r = "UPDATE ROLE SET LIBELLE='"+o.getLibelle()+ "' WHERE IDROLE="+o.getIdrole();
			
			this.dblink.setPst(this.dblink.getConnection().prepareStatement(r));
			this.dblink.getPst().executeQuery();
		}
		catch(SQLException se) {
			System.out.println("Erreur de requ�te : " + se);
		}
		finally{
			this.dblink.deconnexion();
		}
	}

	@Override
	public void delete(Role persistentObject) {
		try {
			dblink.connexion();
			this.dblink.setPst(this.dblink.getConnection().prepareStatement("DELETE FROM ROLE WHERE IDROLE = " + persistentObject.getIdrole()));
		} catch (SQLException e) {
			e.printStackTrace();
		}
		finally{
			dblink.deconnexion();
		}
	}
}
